<?php

namespace Icsoc\MenuBundle\Controller;

use Icsoc\CoreBundle\Controller\BaseController;
use Icsoc\MenuBundle\Entity\Menu;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Icsoc\CoreBundle\Logger\ActionLogger;
use Symfony\Component\Routing\Exception\RouteNotFoundException;

/**
 * 菜单管理
 * Class DefaultController
 * @package Icsoc\MenuBundle\Controller
 */
class DefaultController extends BaseController
{
    const UPLOAD_DIR = '/menu';

    /**
     * 菜单列表
     *
     * @param int $flag
     * @return Response
     */
    public function menuAction($flag)
    {
        if ($flag) {
            $em = $this->getDoctrine()->getManager();
            $all = $em->getRepository('IcsocMenuBundle:Menu')->getTree(0);
            $res = array();
            foreach ($all as $val) {
                $val['menu_text'] = $val['html'].$val['menu_text'];
                if (!empty($val['menu_url'])) {
                    try {
                        $val['menu_url'] = $this->generateUrl($val['menu_url']);
                    } catch (RouteNotFoundException $e) {
                        $val['menu_url'] = '';
                    }
                }
                $res[] = array(
                    'id'=>$val['id'],
                    'menu_text'=>$val['menu_text'],
                    'menu_url'=>$val['menu_url'],
                    'menu_icon'=>$val['menu_icon'],
                    'sort_weight'=>$val['sort_weight'],
                    'help_url'=>$val['help_url'],
                    'is_show'=>$val['is_show'],
                );
            }
            $serializer = $this->get('serializer');
            $response = $serializer->serialize($res, 'json');

            return new Response($response);
        }

        return $this->render('IcsocMenuBundle:Default:menu.html.twig');
    }

    /**
     * @param Request $request
     * @return Response
     * 添加菜单
     */
    public function addMenuAction(Request $request)
    {
        $menu = new Menu();
        $form = $this->createForm('menu', $menu);
        $form->handleRequest($request);
        if ($form->isValid() && $request->getMethod() == 'POST') {
            $em = $this->getDoctrine()->getManager();
            $file = $menu->getFile()->getPathname();
            $fileName = self::UPLOAD_DIR.'/'.$menu->getFile()->getClientOriginalName();
            $this->get("icsoc_filesystem")->putStream($fileName, fopen($file, 'r'));
            $menu->setHelpUrl($fileName);
            //$menu->upload();
            $em->persist($menu);
            if ($menu->getParentId()) {
                //更新父类是否具有子菜单；
                /** @var \Icsoc\MenuBundle\Entity\Menu $parentMenu */
                $parentMenu = $em->getRepository("IcsocMenuBundle:Menu")->find($menu->getParentId());
                $parentMenu->setHasChildren(1);
            }
            $logStr = $this->get('translator')->trans('Add menu %str%', array('%str%'=>$menu->getMenuText()));
            $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_ADD, $logStr);
            $em->flush();
            $data = array(
                'data'=>array(
                    'msg_detail'=>$this->trans('Add menu success'),
                    'type'=>'success',
                    'link' => array(
                        array(
                            'text'=>$this->trans('The menu to add'), 'href'=>$this->generateUrl('icsoc_menu_ment_new'),
                        ),
                        array('text'=>$this->trans('Menu list'), 'href'=>$this->generateUrl('icsoc_menu_homepage')),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }
        //$this->get('icsoc_bread')->add("系统管理")->add("菜单管理", $this->generateUrl('icsoc_menu_homepage'))->add("添加菜单");
        return $this->render('IcsocMenuBundle:Default:new.html.twig', array(
            'form' => $form->createView(),
            'id' => '',
        ));
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * 删除
     */
    public function operMenuAction(Request $request)
    {
        $oper = $request->get('oper', 'del');
        $id = $request->get('id', 0);
        /** @var  $em */
        $em = $this->getDoctrine()->getManager();
        if ($oper == "del" && !empty($id)) {
            //删除；
            /** @var \Icsoc\MenuBundle\Entity\Menu $intro */
            $intro = $em->getRepository('IcsocMenuBundle:Menu')->find($id);
            $parentId = $intro->getParentId();
            $hashChild = $intro->getHasChildren();
            if ($hashChild > 0) {
                return new JsonResponse(
                    array(
                        'message'=>$this->trans('The classification subclasses exist'),
                        'error'=>1,
                    )
                );
            }
            $logStr = $this->get('translator')->trans('Delete menu %str%', array('%str%'=>$intro->getMenuText()));
            $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_DELETE, $logStr);
            $em->remove($intro);
            $em->flush();
            if ($parentId) {
                $parent = $em->getRepository("IcsocMenuBundle:Menu")->findBy(array('parentId'=>$parentId));
                if (!$parent) {
                    $em->getRepository('IcsocMenuBundle:Menu')->find($parentId)->setHasChildren(0);
                    $em->flush();
                }
            }

            return new JsonResponse(array('message'=>$this->trans('Delete success'), 'error'=>0));
        }

        return new JsonResponse(array('message'=>$this->trans('Delete fail'), 'error'=>1));
    }

    /**
     * @param Request $request
     * @return Response
     * 编辑
     */
    public function editMenuAction(Request $request)
    {
        $id = (int) $request->get('id', 0);
        $menu = $this->getDoctrine()->getRepository("IcsocMenuBundle:Menu")->find($id);
        $oldMenu = array('menu_text'=>$menu->getMenuText(), 'menu_url'=>$menu->getMenuUrl());
        $form = $this->createForm("menu", $menu);
        $flySys = $this->get("icsoc_filesystem");
        $form->handleRequest($request);
        if ($form->isValid() && $request->getMethod() == 'POST') {
            $em = $this->getDoctrine()->getManager();
            if ($menu->getFile() != null) {
                //说明上传了文件；删除原文件；
                //@unlink($menu->getAbsolutePath());
                //$menu->upload(); //在上传文件;
                $file = $menu->getFile()->getPathname();
                $fileName = self::UPLOAD_DIR.'/'.$menu->getFile()->getClientOriginalName();
                $flySys->putStream($fileName, fopen($file, 'r'));
                $menu->setHelpUrl($fileName);
            }
            $newMenu = array('menu_text'=>$menu->getMenuText(), 'menu_url'=>$menu->getMenuUrl());
            $diff = array_diff_assoc($oldMenu, $newMenu);
            $logStr = '';
            foreach ($diff as $k => $val) {
                $logStr.="[".$k."]:".$oldMenu[$k]."=>".$newMenu[$k]." ";
            }
            if (!empty($logStr)) {
                $logStr = $this->get('translator')->trans('Update menu %str%', array('%str%'=>$logStr));
                $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_UPDATE, $logStr);
            }
            $em->flush();
            $data = array(
                'data'=>array(
                    'msg_detail'=>$this->trans('Update menu success'),
                    'type' => 'success',
                    'link' => array(
                        array(
                            'text'=>$this->trans('The menu to add'), 'href'=>$this->generateUrl('icsoc_menu_ment_new'),
                        ),
                        array('text'=>$this->trans('Menu list'), 'href'=>$this->generateUrl('icsoc_menu_homepage')),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }

        return $this->render('IcsocMenuBundle:Default:new.html.twig', array(
            'form' => $form->createView(),
            'id' => $id,
        ));
    }

    /**
     * 检测才是否存在
     * @param Request $request
     * @return Response
     */
    public function menuCheckAction(Request $request)
    {
        $name = $request->get('name', '');
        $parentId = $request->get('parentId', '');
        $id = $request->get('id');
        $em = $this->getDoctrine()->getManager();
        if ($id) {
            //修改
            $res = $em->getRepository("IcsocMenuBundle:Menu")->createQueryBuilder('m')
                ->where('m.menuText = :menuText AND m.parentId = :parentId AND m.id <> :id')
                ->setParameters(array('menuText'=>$name, 'parentId'=>$parentId, 'id'=>$id))
                ->getQuery()->getResult();
        } else {
            $res = $em->getRepository("IcsocMenuBundle:Menu")
                ->findOneBy(array('menuText'=>$name, 'parentId'=>$parentId));
        }
        if ($res) {
            return new Response("false");
        } else {
            return new Response("true");
        }
    }
}
